<?php
// +----------------------------------------------------------------------
// | QSCMS
// +----------------------------------------------------------------------
// | Copyright (c)  2025 https://www.qqss.net All rights reserved.
// +----------------------------------------------------------------------
// | Licensed QSCMS is not free software, commercial use must purchase official license from official website to avoid unnecessary legal disputes.
// +----------------------------------------------------------------------
// | Author: Contract 990504246@qq.com
// +----------------------------------------------------------------------

namespace app\web\controller;

use app\common\model\Goods as GoodsModel;
use app\common\model\GoodsComment as GoodsCommentModel;
use app\common\model\CommentLike;
use app\common\model\User as UserModel;
use app\service\uploads\UploadService;

/**
 * Web评论控制器
 */
class Comment extends Base
{
    /**
     * 获取商品评论列表
     */
    public function lists()
    {
        // 支持GET和POST参数
        $goods_id = $this->request->input('goods_id', 0);
        $page     = $this->request->input('page', 1);
        $limit    = $this->request->input('limit', 5);
        $order_by = $this->request->input('sort', 'create_time');

        if (empty($goods_id)) {
            return $this->error('参数错误');
        }

        $goods = GoodsModel::where('status', 1)->find($goods_id);
        if (!$goods) {
            return $this->error(trans('goods_not_exists'));
        }

        // 构建排序规则
        $order_field = 'create_time';
        $order_type  = 'asc';

        if ($order_by == 'create_time') {
            $order_field = 'create_time';
            $order_type  = 'desc';
        } elseif ($order_by == 'likes') {
            $order_field = 'likes';
            $order_type  = 'desc';
        } elseif ($order_by == 'reply_time') {
            $order_field = 'create_time';
            $order_type  = 'asc';
        }

        // 获取评论列表
        $query = GoodsCommentModel::with(['user' => function ($query) {
            $query->field('id,username,avatar,nickname');
        },
            'replies' => function ($query) {
                $query->with(['user' => function ($subQuery) {
                    $subQuery->field('id,username,avatar,nickname');
                }
                ])->where('status', GoodsCommentModel::STATUS_APPROVED)
                    ->field('id,goods_id,user_id,content,parent_id,create_time,update_time,likes')
                    ->order('create_time', 'asc');
            }
        ])
            ->where([
                'goods_id'  => $goods_id,
                'status'    => GoodsCommentModel::STATUS_APPROVED,
                'parent_id' => 0  // 只查询一级评论
            ])
            ->field('id,goods_id,user_id,content,parent_id,create_time,update_time,likes')
            ->order($order_field, $order_type);

        $total    = $query->count();
        $comments = $query->page($page, $limit)->select();

        // 处理评论数据
        $comments->each(function ($item) {
            // 检查当前用户是否点赞了这条评论
            if ($this->user_id) {
                $item->is_liked = CommentLike::where([
                    'user_id'    => $this->user_id,
                    'comment_id' => $item->id
                ])->count() > 0;
            } else {
                $item->is_liked = false;
            }

            // 处理内容中的图片和附件
            $this->processCommentContent($item);

            // 处理回复数据
            if ($item->replies) {
                $item->replies->each(function ($reply) {
                    // 检查当前用户是否点赞了这条回复
                    if ($this->user_id) {
                        $reply->is_liked = CommentLike::where([
                            'user_id'    => $this->user_id,
                            'comment_id' => $reply->id
                        ])->count() > 0;
                    } else {
                        $reply->is_liked = false;
                    }

                    // 处理回复内容中的图片和附件
                    $this->processCommentContent($reply);
                });
            }
        });

        return $this->success('获取成功', [
            'list'     => $comments,
            'total'    => $total,
            'page'     => $page,
            'limit'    => $limit,
            'has_more' => $total > $page * $limit
        ]);
    }

    /**
     * 提交评论
     */
    public function submit()
    {
        if (!$this->user_id) {
            return $this->error('请先登录');
        }

        // 检查用户是否设置了昵称
        $user = UserModel::find($this->user_id);
        if (!$user) {
            return $this->error('用户不存在');
        }
        if (empty($user->nickname)) {
            return $this->error('请先设置一个昵称吧');
        }

        $goods_id    = $this->request->post('goods_id', 0);
        $content     = trim($this->request->post('content', ''));
        $parent_id   = $this->request->post('parent_id', 0);
        $images      = $this->request->post('images', []);
        $attachments = $this->request->post('attachments', []);

        // 参数验证
        if (empty($goods_id)) {
            return $this->error('商品ID不能为空');
        }

        if (empty($content)) {
            return $this->error('评论内容不能为空');
        }

        $minLength = $parent_id > 0 ? 2 : 5; // 回复最少2个字符，评论最少5个字符
        if (mb_strlen($content) < $minLength) {
            return $this->error('评论内容至少需要' . $minLength . '个字符');
        }

        if (mb_strlen($content) > 500) {
            return $this->error('评论内容不能超过500字');
        }

        // 检查商品是否存在
        $goods = GoodsModel::where('status', 1)->find($goods_id);
        if (!$goods) {
            return $this->error(trans('goods_not_exists'));
        }

        // 如果是回复，验证父评论是否存在
        if ($parent_id > 0) {
            $parentComment = GoodsCommentModel::find($parent_id);
            if (!$parentComment) {
                return $this->error('回复的评论不存在');
            }
        }

        // 处理图片和附件，将它们嵌入到内容中
        $processedContent = $content;

        // 添加图片标签
        if (!empty($images)) {
            foreach ($images as $image) {
                $processedContent .= '<img src="' . htmlspecialchars($image) . '" alt="评论图片" />';
            }
        }

        // 添加附件链接
        if (!empty($attachments)) {
            foreach ($attachments as $attachment) {
                $fileName         = basename($attachment);
                $processedContent .= '<a href="' . htmlspecialchars($attachment) . '" data-type="file">' . htmlspecialchars($fileName) . '</a>';
            }
        }

        // 创建评论
        $comment_data = [
            'goods_id'    => $goods_id,
            'user_id'     => $this->user_id,
            'content'     => $processedContent,
            'parent_id'   => $parent_id,
            'status'      => GoodsCommentModel::STATUS_APPROVED,
            'is_admin'    => 0,
            'likes'       => 0,
            'create_time' => date('Y-m-d H:i:s'),
            'update_time' => date('Y-m-d H:i:s')
        ];

        try {
            $comment = GoodsCommentModel::create($comment_data);

            // 如果是回复，更新父评论的更新时间
            if ($parent_id > 0) {
                GoodsCommentModel::where('id', $parent_id)->update(['update_time' => date('Y-m-d H:i:s')]);
            } else {
                // 只有一级评论才更新商品评论计数
                $goods->setInc('comments_count');
            }

            return $this->success('评论提交成功', [
                'comment_id'  => $comment->id,
                'create_time' => $comment->create_time
            ]);
        } catch (\Exception $e) {
            return $this->error('评论提交失败，请稍后重试');
        }
    }

    /**
     * 点赞/取消点赞评论
     */
    public function like()
    {
        if (!$this->user_id) {
            return $this->error('请先登录');
        }

        $comment_id = $this->request->post('comment_id', 0);
        if (empty($comment_id)) {
            return $this->error('评论ID不能为空');
        }

        $comment = GoodsCommentModel::where('id', $comment_id)->find();
        if (!$comment) {
            return $this->error('评论不存在');
        }

        if ($comment->user_id == $this->user_id) {
            return $this->error('不能给自己的评论点赞');
        }

        // 检查用户是否已点赞该评论
        $existingLike = CommentLike::where([
            'user_id'    => $this->user_id,
            'comment_id' => $comment_id
        ])->find();

        try {
            if ($existingLike) {
                // 取消点赞
                $existingLike->delete();
                $comment->setDec('likes');

                return $this->success('取消点赞成功', [
                    'is_liked' => false,
                    'likes'    => max(0, $comment->likes - 1)
                ]);
            } else {
                // 添加点赞
                CommentLike::create([
                    'user_id'     => $this->user_id,
                    'comment_id'  => $comment_id,
                    'create_time' => date('Y-m-d H:i:s')
                ]);
                $comment->setInc('likes');

                return $this->success('点赞成功', [
                    'is_liked' => true,
                    'likes'    => $comment->likes + 1
                ]);
            }
        } catch (\Exception $e) {
            return $this->error('操作失败，请稍后重试');
        }
    }

    /**
     * 删除评论（用户只能删除自己的评论）
     */
    public function delete()
    {
        if (!$this->user_id) {
            return $this->error('请先登录');
        }

        $comment_id = $this->request->post('comment_id', 0);
        if (empty($comment_id)) {
            return $this->error('评论ID不能为空');
        }

        $comment = GoodsCommentModel::where([
            'id'      => $comment_id,
            'user_id' => $this->user_id
        ])->find();

        if (!$comment) {
            return $this->error('评论不存在或无权删除');
        }

        try {
            // 删除评论的点赞记录
            CommentLike::where('comment_id', $comment_id)->delete();

            // 删除评论
            $comment->delete();

            // 更新商品评论计数
            $goods = GoodsModel::find($comment->goods_id);
            if ($goods) {
                $goods->setDec('comments_count');
            }

            return $this->success('评论删除成功');
        } catch (\Exception $e) {
            return $this->error('删除失败，请稍后重试');
        }
    }

    /**
     * 上传评论图片
     */
    public function uploadImage()
    {
        if (!$this->user_id) {
            return $this->error('请先登录');
        }

        try {
            $file = $this->request->file('file');
            if (!$file || !$file->isValid()) {
                return $this->error('请选择要上传的图片');
            }

            // 使用UploadService处理上传，更加稳定和统一
            $res = (new UploadService())->upload('user', $file, 'image', $this->user_id);

            return $this->success('上传成功', $res);

        } catch (\Exception $e) {
            return $this->error('上传失败: ' . $e->getMessage());
        }
    }

    /**
     * 上传评论附件
     */
    public function uploadAttachment()
    {
        if (!$this->user_id) {
            return $this->error('请先登录');
        }

        try {
            $file = $this->request->file('file');
            if (!$file || !$file->isValid()) {
                return $this->error('请选择要上传的文件');
            }

            // 使用UploadService处理上传，支持所有文件类型
            $res = (new UploadService())->upload('user', $file, 'all', $this->user_id);

            return $this->success('上传成功', $res);

        } catch (\Exception $e) {
            return $this->error('上传失败: ' . $e->getMessage());
        }
    }

    /**
     * 获取评论回复
     */
    public function replies()
    {
        $comment_id = $this->request->get('comment_id', 0);
        $page       = $this->request->get('page', 1);
        $limit      = $this->request->get('limit', 10);

        if (empty($comment_id)) {
            return $this->error('参数错误');
        }

        // 检查评论是否存在
        $parentComment = GoodsCommentModel::where([
            'id'     => $comment_id,
            'status' => GoodsCommentModel::STATUS_APPROVED
        ])->find();

        if (!$parentComment) {
            return $this->error('评论不存在');
        }

        // 获取回复列表
        $query = GoodsCommentModel::with(['user' => function ($query) {
            $query->field('id,username,avatar,nickname');
        }
        ])
            ->where([
                'parent_id' => $comment_id,
                'status'    => GoodsCommentModel::STATUS_APPROVED
            ])
            ->field('id,goods_id,user_id,content,parent_id,create_time,update_time,likes')
            ->order('create_time', 'asc');

        $total   = $query->count();
        $replies = $query->page($page, $limit)->select();

        // 处理回复数据
        $replies->each(function ($item) {
            // 检查当前用户是否点赞了这条回复
            if ($this->user_id) {
                $item->is_liked = CommentLike::where([
                    'user_id'    => $this->user_id,
                    'comment_id' => $item->id
                ])->count() > 0;
            } else {
                $item->is_liked = false;
            }

            // 处理内容中的图片和附件
            $this->processCommentContent($item);

        });

        return $this->success('获取成功', [
            'list'     => $replies,
            'total'    => $total,
            'page'     => $page,
            'limit'    => $limit,
            'has_more' => $total > $page * $limit
        ]);
    }

    /**
     * 处理评论内容中的图片和附件
     */
    private function processCommentContent($comment)
    {
        if (!$comment->content) {
            return;
        }

        // 提取并移除图片标签
        $imgRegex = '/<img[^>]+src="([^"]+)"[^>]*>/';
        preg_match_all($imgRegex, $comment->content, $imgMatches);
        if (!empty($imgMatches[1])) {
            $comment->images  = $imgMatches[1];
            $comment->content = preg_replace($imgRegex, '', $comment->content);
        }

        // 提取并移除文件链接
        $fileRegex = '/<a[^>]+href="([^"]+)"[^>]*data-type="file"[^>]*>([^<]+)<\/a>/';
        preg_match_all($fileRegex, $comment->content, $fileMatches);
        if (!empty($fileMatches[1])) {
            $attachments = [];
            for ($i = 0; $i < count($fileMatches[1]); $i++) {
                $attachments[] = [
                    'url'  => $fileMatches[1][$i],
                    'name' => $fileMatches[2][$i],
                    'type' => 'file'
                ];
            }
            $comment->attachments = $attachments;
            $comment->content     = preg_replace($fileRegex, '', $comment->content);
        }

        // 清理内容中的多余空白
        $comment->content = trim($comment->content);
    }
}
